package com.kongfuzi.student.support.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by cfan_yang on 2015/12/16.
 */
public class MD5Util {
    public static String encode(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            //拼接一个字符串
            password = "nxxjmpf_nxxjmpf_nxxjmpf_nxxjmpf_nxxjmpf_nxxjmpf_nxxjmpf" + password;
            byte[] bs = digest.digest(password.getBytes());

            StringBuffer sb = new StringBuffer();
            for (byte b : bs) {
                int i = b & 0xff;// 获取该字节的低八位信息, 11111111

                String hexString = Integer.toHexString(i);

                if (hexString.length() < 2) {
                    hexString = "0" + hexString;
                }

                sb.append(hexString);
            }

            return sb.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            // 没有该算法时会走此异常
            e.printStackTrace();
        }

        return "";
    }

    public final static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}
